package com.serviceprovider.business.module.admin.user.model;

//~--- non-JDK imports --------------------------------------------------------

import com.serviceprovider.business.module.common.Page;
import com.serviceprovider.business.module.user.model.forms.EditUserForm;
import com.serviceprovider.business.module.user.model.forms.ViewUserForm;
import com.serviceprovider.business.module.user.model.impl.User;
import com.serviceprovider.business.module.user.model.impl.UserManager;
import com.serviceprovider.business.module.user.model.impl.UserSearchCriteria;
import com.serviceprovider.business.module.user.model.interfaces.IElements;

import org.springframework.stereotype.Repository;
import org.springframework.validation.BindingResult;
import org.springframework.web.servlet.ModelAndView;

//~--- JDK imports ------------------------------------------------------------

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Leonardo A. Auer
 * @since 04/11/2011
 */

/**
 * Implementation of UserManager class.
 * This class manages all request received from
 * user controller when user connected is ROLE_SERVICE_PROVIDER
 */
@Repository("adminManager")
public class AdminManager extends UserManager {

/*
    @Override
    public ModelAndView viewUsers(HttpServletRequest request, HttpSession session, BindingResult result) {

            ModelAndView mav = new ModelAndView("/users/view_users");
            int recordSize = applicationConfigProperties.getRecordSize("view_users.records.size");

            Page<User> userList = userService.findAll(1, recordSize,"id","asc");
            userService.retrieveLevel1User(userList.getPageItems());
            roleService.retrieveRole(userList.getPageItems());

            mav.addObject("userList", userList);
            mav.addObject("viewUserForm", new ViewUserForm());
            mav.addObject("elements", getElementsInstance());
            return mav;
    }
*/
    @Override
    public ModelAndView searchUsersPost(HttpServletRequest request, HttpSession session, ViewUserForm viewUserForm,
            BindingResult result) {
        UserSearchCriteria criteria = (UserSearchCriteria) session.getAttribute("criteria");

        if (criteria == null) {
            criteria = new UserSearchCriteria();
            session.setAttribute("criteria", criteria);
        }

        return searchUsers(request, criteria, viewUserForm, result);
    }

    protected void validateEmailEfin(EditUserForm editUserForm, BindingResult result) {

        // Check email to be unique
        UserSearchCriteria checkCriteria = new UserSearchCriteria();

        checkCriteria.setEmail(editUserForm.getEmail());

        Page<User> checkUsers = userService.findUserByCriteria(checkCriteria, 1, 1, "email", "desc");

        if (checkUsers.getTotalRecords() > 0) {
            result.rejectValue("email", "email.already.exists");
        }

        checkCriteria.setEmail(null);

        if (editUserForm.getEfin() != null) {
            checkCriteria.setEfin(editUserForm.getEfin());
            checkUsers = userService.findUserByCriteria(checkCriteria, 1, 1, "efin", "desc");

            if (checkUsers.getTotalRecords() > 0) {
                result.rejectValue("efin", "efin.already.exists");
            }
        }
    }

    @Override
    public ModelAndView createUser(EditUserForm editUserForm, BindingResult result) {
        validator.validate(editUserForm, result);
        validateEmailEfin(editUserForm, result);

        if (result.hasErrors()) {
            ModelAndView mav = new ModelAndView("/users/create_user");

            mav.addObject("elements", getElementsInstance());

            return mav;
        }

        User newUser = createUser(editUserForm);

        preferencesService.saveDefaultFee(newUser, editUserForm.getFee());

        return new ModelAndView("redirect:/users/view_users.htm");
    }

    @Override
    public ModelAndView viewUserDetails(int userId, Boolean saveSuccess) {
        User         user         = getUserDetailed(userId);
        ViewUserForm viewUserForm = new ViewUserForm(user);

        if (saveSuccess != null) {
            viewUserForm.setSaveSuccess(saveSuccess);
        }

        ModelAndView mav = new ModelAndView("/users/view_user_details");

        mav.addObject("viewUserForm", viewUserForm);
        mav.addObject("elements", getElementsInstance());
        mav.addObject("level1Users", userService.findAll());

        return mav;
    }

    @Override
    public ModelAndView editUserDetails(HttpServletRequest request) {
        int userId;

        try {
            userId = Integer.parseInt(request.getParameter("id"));
        } catch (NumberFormatException e) {
            return new ModelAndView("redirect:/users/view_users.htm");
        }

        User         user         = getUserDetailed(userId);
        EditUserForm editUserForm = new EditUserForm(user);
        User         currentUser  = userService.getUserConnected();

        currentUser.setRole(roleService.getRoleById(currentUser.getRole().getId()));
        editUserForm.setCurrentUser(currentUser);

        ModelAndView mav = new ModelAndView("/users/edit_user_details");

        mav.addObject("userForm", editUserForm);
        mav.addObject("level1Users", userService.findAll());
        mav.addObject("elements", getElementsInstance());

        return mav;
    }

    @Override
    public IElements getElementsInstance() {
        return new AdminElements();
    }
}



